import React, { Component } from 'react'
import { Modal, Form, Input, Button, Row, Col, Upload, message } from 'antd'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'

import { sendsms, register } from '@/api/user'

export default class Register extends Component {
  constructor () {
    super()

    this.state = {
      isModalVisible: false, // 控制窗口显示或是隐藏
      registerCaptchaUrl:
        process.env.REACT_APP_BASEURL + '/captcha?type=sendsms',
      uploadUrl: process.env.REACT_APP_BASEURL + '/uploads',
      imageUrl: '', // 预览的地址
      loading: false, // 是否正在上传图片过程中
      fileList: [] // 已经上传的文件列表（受控）
    }
  }

  // 上传时候，需要携带的额外参数
  uploadObj = {
    image: null
  }

  // 更改图形码的地址
  changeRegisterCaptchaUrl = () => {
    this.setState({
      registerCaptchaUrl:
        process.env.REACT_APP_BASEURL +
        `/captcha?type=sendsms&t=${new Date() - 0}`
    })
  }

  formRef = React.createRef()

  handleOk = async () => {
    try {
      const values = await this.formRef.current.validateFields()

      // 调用注册接口
      const res = await register(values)
      if (res.code === 200) {
        message.success('注册成功~')

        this.closeModal()
      } else {
        message.error(res.message)

        this.changeRegisterCaptchaUrl()
      }

      // 发请求，完成注册
    } catch (error) {
      console.log(error)
    }
  }

  handleCancel = () => {
    this.closeModal()
  }

  closeModal = () => {
    this.setState({
      isModalVisible: false
    })

    // 清空内容
    this.formRef.current.resetFields()

    // 清空头像上传的预览
    this.setState({
      imageUrl: ''
    })
  }

  layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 }
  }

  // 上传头像操作
  // 上传之前
  beforeUpload = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('你只能上传 JPG/PNG 格式的图片!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!')
    }

    this.uploadObj.image = file
    return isJpgOrPng && isLt2M
  }

  // 上传之后
  getBase64 = (img, callback) => {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }

  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true })
      return
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false
        })
      )

      // 判断是否正确传递给了后台
      if (info.file.response.code === 200) {
        this.formRef.current.setFieldsValue({
          avatar: info.file.response.data.file_path
        })
      } else {
        message.error(info.file.response.message)
      }
    }
  }

  // 获取验证码
  getVCode = async () => {
    try {
      const values = await this.formRef.current.validateFields([
        'phone',
        'code'
      ])

      const res = await sendsms(values)
      if (res.code !== 200) {
        message.error(res.message)

        this.changeRegisterCaptchaUrl()
      } else {
        // 给验证码框赋值
        this.formRef.current.setFieldsValue({
          rcode: res.data.captcha
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  render () {
    const { imageUrl, loading, fileList } = this.state
    return (
      <div>
        <Modal
          title='用户注册'
          visible={this.state.isModalVisible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText='确定'
          cancelText='取消'
          width={600}
        >
          <Form
            name='normal_login'
            style={{ marginTop: 20 }}
            labelAlign='left'
            initialValues={{}}
            size='large'
            ref={this.formRef}
          >
            <Form.Item
              label='头像'
              name='avatar'
              rules={[
                {
                  required: true,
                  message: '图像不能为空'
                }
              ]}
              validateTrigger='onBlur'
            >
              <Upload
                name='avatar'
                listType='picture-card'
                className='avatar-uploader'
                showUploadList={false}
                action={this.state.uploadUrl}
                data={this.uploadObj}
                beforeUpload={this.beforeUpload}
                onChange={this.handleChange}
                fileList={fileList}
              >
                {imageUrl ? (
                  <img
                    src={imageUrl}
                    alt='avatar'
                    style={{ width: '100%', height: '100%' }}
                    alt=''
                  />
                ) : (
                  <div>{loading ? <LoadingOutlined /> : <PlusOutlined />}</div>
                )}
              </Upload>
            </Form.Item>
            <Form.Item
              label='昵称'
              name='username'
              rules={[
                {
                  required: true,
                  message: '昵称不能为空'
                }
              ]}
              validateTrigger='onBlur'
            >
              <Input />
            </Form.Item>
            <Form.Item
              label='邮箱'
              name='email'
              rules={[
                {
                  required: true,
                  message: '邮箱不能为空'
                },
                {
                  type: 'email',
                  message: '邮箱不合法'
                }
              ]}
              validateTrigger='onBlur'
            >
              <Input />
            </Form.Item>
            <Form.Item
              name='phone'
              label='手机'
              rules={[
                {
                  required: true,
                  validator: (_, value) => {
                    if (!value) return Promise.reject('手机号不能为空')

                    const reg = /^1[3456789][0-9]{9}$/
                    if (!reg.test(value)) return Promise.reject('手机号不合法')

                    return Promise.resolve()
                  }
                }
              ]}
              validateTrigger='onBlur'
            >
              <Input />
            </Form.Item>
            <Form.Item
              name='password'
              label='密码'
              rules={[
                {
                  required: true,
                  message: '密码不能为空'
                },
                {
                  min: 6,
                  max: 16,
                  message: '密码长度需要在6-16位之间'
                }
              ]}
              validateTrigger='onBlur'
            >
              <Input type='password' />
            </Form.Item>
            <Row>
              <Col span={16}>
                <Form.Item
                  name='code'
                  label='图形码'
                  rules={[
                    {
                      required: true,
                      message: '图形码不能为空'
                    }
                  ]}
                  validateTrigger='onBlur'
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col style={{ marginLeft: 15 }} span={7}>
                <img
                  src={this.state.registerCaptchaUrl}
                  style={{ width: '100%', height: 40 }}
                  alt=''
                  onClick={this.changeRegisterCaptchaUrl}
                />
              </Col>
            </Row>
            <Row>
              <Col span={16}>
                <Form.Item
                  name='rcode'
                  label='验证码'
                  rules={[
                    {
                      required: true,
                      message: '验证码不能为空'
                    }
                  ]}
                  validateTrigger='onBlur'
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col style={{ marginLeft: 15 }} span={7}>
                <Button onClick={this.getVCode}>获取用户验证码</Button>
              </Col>
            </Row>
          </Form>
        </Modal>
      </div>
    )
  }
}
